﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Collections.Specialized;
using System.IO;

namespace moni
{
    public class MyServlet : Servlet
    {
        private FormMain formMain;

        public MyServlet(FormMain formMain)
        {
            this.formMain = formMain;
        }

        public override void onCreate()
        {
            base.onCreate();
        }

        public override void onGet(HttpListenerRequest request, HttpListenerResponse response)
        {
            Console.WriteLine("GET:" + request.Url);
            string rawUrl = request.RawUrl;
            if (rawUrl.StartsWith("/position"))
            {
                List<Data> list = formMain.getCurrentPosition();
                JsonSerializer serializer = new JsonSerializer();
                StringWriter sw = new StringWriter();
                serializer.Serialize(new JsonTextWriter(sw), list);
                string result = sw.GetStringBuilder().ToString();
                response.ContentType = "application/json";
                response.ContentEncoding = Encoding.UTF8;
                byte[] buffer = Encoding.UTF8.GetBytes(result);
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
            else if (rawUrl.StartsWith("/balance"))
            {
                //获取当前可用余额
                string result = formMain.getCurrentBalance();
                response.ContentType = "application/json";
                response.ContentEncoding = Encoding.UTF8;
                byte[] buffer = Encoding.UTF8.GetBytes(result);
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            } else if (rawUrl.StartsWith("/delegated")) {
                List<DelegatedData> list = formMain.getDelegated();
                JsonSerializer serializer = new JsonSerializer();
                StringWriter sw = new StringWriter();
                serializer.Serialize(new JsonTextWriter(sw), list);
                string result = sw.GetStringBuilder().ToString();
                response.ContentType = "application/json";
                response.ContentEncoding = Encoding.UTF8;
                byte[] buffer = Encoding.UTF8.GetBytes(result);
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
                
            }
        }

        public override void onPost(HttpListenerRequest request, HttpListenerResponse response)
        {
            string ret = "OK";
            string rawUrl = request.RawUrl;
            if (rawUrl.StartsWith("/buy"))
            {
                if (request.HasEntityBody)
                {
                    System.IO.Stream body = request.InputStream;
                    System.Text.Encoding encoding = request.ContentEncoding;
                    System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
                    if (request.ContentType != null)
                    {
                        Console.WriteLine("Client data content type {0}", request.ContentType);
                    }
                    string s = reader.ReadToEnd();
                    Console.WriteLine(s);
                    body.Close();
                    reader.Close();
                    //进行内容解析，发送请求
                    JsonSerializer serializer = new JsonSerializer();
                    Object data = JsonConvert.DeserializeObject<Object>(s);
                    Newtonsoft.Json.Linq.JObject obj = data as Newtonsoft.Json.Linq.JObject;
                    ret = formMain.createOrder(int.Parse(obj["market"].ToString()), obj["code"].ToString(), obj["price"].ToString(), obj["amount"].ToString(), 1);
                }
            }else if (rawUrl.StartsWith("/sell"))
            {
                if (request.HasEntityBody)
                {
                    System.IO.Stream body = request.InputStream;
                    System.Text.Encoding encoding = request.ContentEncoding;
                    System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
                    if (request.ContentType != null)
                    {
                        Console.WriteLine("Client data content type {0}", request.ContentType);
                    }
                    string s = reader.ReadToEnd();
                    Console.WriteLine(s);
                    body.Close();
                    reader.Close();
                    //进行内容解析，发送请求

                    JsonSerializer serializer = new JsonSerializer();
                    Object data = JsonConvert.DeserializeObject<Object>(s);
                    Newtonsoft.Json.Linq.JObject obj = data as Newtonsoft.Json.Linq.JObject;
                    ret = formMain.createOrder(int.Parse(obj["market"].ToString()), obj["code"].ToString(), obj["price"].ToString(), obj["amount"].ToString(), 2);
                }
            }
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            Console.WriteLine("POST:" + request.Url);
            byte[] res = Encoding.UTF8.GetBytes(ret);
            response.ContentLength64 = res.Length;
            response.OutputStream.Write(res, 0, res.Length);
        }
    }
}
